layui.use(['layer', 'form', 'table', 'configs', 'template'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        template = layui.template,
        config = layui.configs;
    var curPage = 1, lastPage = 1;
    //获取表格数据
    getTableData();

    function getTableData(callback) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/select/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    renderTable(result.data);
                    callback && callback();
                } else {
                    layer.msg(result.stateMsg);
                }
            },
        })
    }

    //渲染表格
    function renderTable(data) {
        table.render({
            elem: '.settingTable'
            , id: 'motorsInfo'
            , data: data
            , autoSort: false
            , toolbar: '#toolbarMotors'
            , defaultToolbar: ['filter']
            , cols: [[
                {field: 'areaName', title: '区域'}
                , {field: 'moId', title: '马达ID', width: 75}
                , {field: 'moName', title: '马达名称'}
                , {field: 'useFlag', title: '标志', templet: '<div>{{d.useFlag==1 ? "启用" : "禁用"}}</div>'}
                , {
                    field: 'upperLimit',
                    title: '上限',
                    width: 90,
                    templet: '<div>{{ d.upperLimit == -1? "未启用" : d.upperLimit}}</div>'
                }
                , {
                    field: 'lowerLimit',
                    title: '下限',
                    width: 90,
                    templet: '<div>{{ d.lowerLimit == -1? "未启用" : d.lowerLimit}}</div>'
                }
                , {
                    field: 'upperLimitInner',
                    title: '管制上限',
                    width: 90,
                    templet: '<div>{{ d.upperLimitInner == -1? "未启用" : d.upperLimitInner == null ? "" : d.upperLimitInner}}</div>'
                }
                , {
                    field: 'lowerLimitInner',
                    title: '管制下限',
                    width: 90,
                    templet: '<div>{{ d.lowerLimitInner == -1? "未启用" : d.lowerLimitInner == null ? "" : d.lowerLimitInner}}</div>'
                }
                , {field: 'monitorShow', title: '监测器信息', width: 170}
                , {
                    field: 'periods',
                    title: '马达期别',
                    templet: '<div>{{d.periods==1 ? "一期" : (d.periods==2?"二期":"")}}</div>'
                }
                , {field: 'notes', title: '备注'}
                , {fixed: 'right', title: '操作', width: 230, align: 'center', toolbar: '#rowOperate'}
            ]]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                , groups: 1 //只显示 5 个连续页码
                , first: false
                , last: false
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: 10
            , loading: true
            , done: function (res, curr, count) {
                curPage = curr;
            }
        });
    }

    //头工具栏事件--新增
    table.on('toolbar(setMotorsTable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var event = obj.event;
        if (event === 'addMotors') { //新增
            var layerIdx = layer.open({
                type: 1,
                title: "新增马达",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#newAdd').html(),
                success: function (layero, index) {
                    // var sideType = layero.find("[name='sideType'] option:selected").text();
                    // var sideSort = layero.find("input[name='sideSort']").val();
                    // $(".addInfos input[name='moName']").val(sideType + "-" + sideSort);
                    form.render();
                    getArea(layero);
                    $('.limit-box input[type="text"]').val(-1);
                }
            });

            form.on('submit(AddForm)', function (res) {
                //console.log(res.field)
                var up = + res.field.upperLimit, low = + res.field.lowerLimit;
                if(up == -1 || low == -1){
                    addMotors(res.field);
                    layer.close(layerIdx);
                }else{
                    if(up >= low){
                        addMotors(res.field);
                        layer.close(layerIdx);
                    }else{
                        layer.msg('上限应高于下限！', {icon: 2})
                    }
                }
                return false;
            });
            //取消
            $(".addInfos button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //监听新增-上下限/管制上下限开关
    form.on('switch(switchLimit)', function (data) {
        if (data.elem.checked) {
            $(data.othis).next('input[type="text"]').val("");
            $(data.othis).next('input[type="text"]').removeClass("layui-hide");
        } else {
            $(data.othis).next('input[type="text"]').val(-1);
            $(data.othis).next('input[type="text"]').addClass("layui-hide");
        }
    });
    //监听编辑-上下限/管制上下限开关
    form.on('switch(switchLimitEdit)', function (data) {
        if (data.elem.checked) {
            $(data.othis).next('input[type="text"]').val("");
            $(data.othis).next('input[type="text"]').removeClass("layui-hide");
        } else {
            $(data.othis).next('input[type="text"]').val(-1);
            $(data.othis).next('input[type="text"]').addClass("layui-hide");
        }
    });

    //监听工具条
    table.on('tool(setMotorsTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'del') { //删除
            layer.confirm('真的删除吗？', function (index) {
                layer.close(index);
                deleteMotors(obj, data.moId);
            });
        } else if (layEvent === 'edit') { //编辑
            var layerIdx = layer.open({
                type: 1,
                title: "编辑马达",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#rowEdit').html(),
                success: function (layero, index) {
                    getArea(layero, function () {
                        form.val("rowEditForm", data);
                        var ups = layero.find('.limit-box .upperLimitSwitch');
                        var upls = layero.find('.limit-box .upperLimitInnerSwitch');
                        var upipt = layero.find('.limit-box input[name="upperLimit"]');
                        var uplipt = layero.find('.limit-box input[name="upperLimitInner"]');

                        var ipts = layero.find('.limit-box input[type="text"]');
                        var iptname = "";
                        var sname = "";
                        var obj = {};
                        for (var i = 0; i < ipts.length; i++) {
                            iptname = $(ipts[i]).attr("name");
                            sname = "switch-" + iptname;
                            if (data[iptname] != -1) {
                                obj[sname] = true;
                                $(ipts[i]).removeClass("layui-hide");
                                obj[iptname] = data[iptname];
                                form.val("rowEditForm", obj);
                            }
                        }
                    });
                    form.val("rowEditForm", data);
                }
            });
            form.val("rowEditForm", data);
            form.on('submit(rowEditForm)', function (res) {
                //console.log(res.field);
                var up = + res.field.upperLimit, low = + res.field.lowerLimit;
                if(up == -1 || low == -1){
                    updateMotors(obj, res.field);
                    layer.close(layerIdx);
                }else{
                    if(up >= low){
                        updateMotors(obj, res.field);
                        layer.close(layerIdx);
                    }else{
                        layer.msg('上限应高于下限！', {icon: 2})
                    }
                }
                return false;
            });
            //取消
            $(".editInfos button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        } else if (layEvent === 'install') {
            var layerIdx = layer.open({
                type: 1,
                title: "安装监测器",
                closeBtn: 1,
                anim: 0,
                area: '420px',
                content: $('#installMonitor').html(),
                success: function (layero, index) {
                    getMonitors();
                    form.render();
                }
            });
            form.val("installMonitorForm", data);
            form.on('submit(installMonitorForm)', function (res) {
                //console.log(res.field);
                installMonitor(obj, res.field);
                layer.close(layerIdx);
                return false;
            });
            //取消
            $(".installForm button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        } else if (layEvent === 'uninstall') {
            //form.val("uninstallMonitorForm", data);
            layer.confirm('真的卸载监测器吗？', function (index) {
                layer.close(index);
                uninstallMonitor(obj, data.moId);
            });

        }
    });

    //新增
    function addMotors(dataObj) {
        console.log(dataObj);
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/add/v1.0",
            type: "post",
            datatype: "json",
            data: dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //删除
    function deleteMotors(obj, moId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/delete/v1.0",
            type: "post",
            datatype: "json",
            data: {
                "moId": moId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    layer.alert(result.stateMsg);
                    // getTableData();
                    refreshTable('delete', obj);
                } else {
                    layer.alert(result.stateMsg);
                }

            }
        })
    }

    //更新
    function updateMotors(obj, data) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/update/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    // getTableData();
                    refreshTable('update', obj, data);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //上下限验证
    function limitVerify(field,callback){
        if(field.upperLimit != -1 && field.lowerLimit != -1){
            if(field.upperLimit < field.lowerLimit) {
                layer.msg('上限应高于下限！')
            }
        }else{
            callback();
        }
    }

    function tableReload() {
        table.reload("motorsInfo", {
            url: config.motorBaseUrl + '/mo_motors/select/v1.0'
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
            , page: {
                curr: curPage
            }
        })
    }

    /*表格操作后，保留在当页
    * obj ： 表格自身参数
    * data： 更新或删除的对象
    * type： delete 、update 、install 、 uninstall
    * */
    function refreshTable(type, obj, data) {
        if (type == "update") {
            obj.update(data); //同步更新缓存对应的值
        } else if (type == "delete") {
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        } else if (type == "install") {
            getTableData(fn);
        } else if (type == "uninstall") {
            getTableData(fn);
        }

        function fn() {
            // console.log("lastPage="+lastPage+"  ;  curPage="+ curPage);
            $(".layui-laypage-skip input.layui-input").val(lastPage);
            $(".layui-laypage-btn")[0].click();
        }
    }

    function getArea(layero, callback) {
        $.ajax({
            url: config.motorBaseUrl + "/area_info/select/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    layero.find($(".areaMenu")).html(template("motor-areas-tpl", result));
                    form.render();
                    callback && callback();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        });
    }

    //显示所有待安装的感应器
    function getMonitors(callback) {
        $.ajax({
            url: config.motorBaseUrl + "/monitors/caninstalled/v1.0",
            type: "post",
            datatype: "json",
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".monitors").html(template("install-tpl", result));
                    form.render('select');
                    callback && callback();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        });
    }

    function installMonitor(obj, data) {
        var moId = data.moId;
        var monitorId = data.monitorId;
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/install_monitor/v1.0",
            type: "post",
            datatype: "json",
            data: {
                moId: moId,
                monitorId: monitorId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    lastPage = curPage;
                    refreshTable('install', obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    function uninstallMonitor(obj, moId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/uninstall_monitor/v1.0",
            type: "post",
            datatype: "json",
            data: {moId: moId},
            success: function (result) {
                if (result.stateCode == 0) {
                    lastPage = curPage;
                    refreshTable('install', obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

});